package cn.sdxx.qddata.controller;

import cn.sdxx.qddata.common.R;
import cn.sdxx.qddata.utils.JwtTokenUtils;
import cn.sdxx.qddata.utils.VerifyCodeUtil;
import cn.sdxx.qddata.vo.VerifyCodeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "Code模块")
@Slf4j
@RestController
@RequestMapping("/code")
public class CodeController {


    //  Chrome 84以上会有同站策略， 弃用通过session校验，引入redis来做判断验证码
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;


    @ApiOperation(value = "获取图片验证码的接口", notes = "仅支持获取，无法验证")
    @GetMapping
    public void getCode(HttpServletRequest request, HttpServletResponse response) {

        /*
         * This Set-Cookie didn't specify a "SameSite" attribute, was defaulted to "SameSite=Lax",
         *   Chrome 84以上会有同站策略
         *  这个方案不能解决：https://blog.csdn.net/seapeak007/article/details/122811192
         * */

        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);

            String verifyCode = VerifyCodeUtil.generateVerifyCode(4);//生成4位验证码
            //向客户端输出验证码图片
            ServletOutputStream outputStream = response.getOutputStream();
            VerifyCodeUtil.outputImage(100,40,outputStream,verifyCode); //将验证码的图片流发至前端

        } catch (Exception e) {
            log.error("获取验证码失败!", e);
        }

    }

    /**
     * 获取登录图片验证码
     */
    @ApiOperation(value = "获取图片验证码base64接口",notes = "支持验证")
    @GetMapping(value = "/captcha")
    public R getCaptchaCode() {
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);//生成4位验证码
        // 验证码标识
        String codeKey = jwtTokenUtils.generateToken(verifyCode);
        String redisCodekey = "CODE_KEY_" + codeKey;
        redisTemplate.opsForValue().set(redisCodekey, verifyCode, 1, TimeUnit.MINUTES);
        // 将图像输出到Servlet输出流中。
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            VerifyCodeUtil.outputImage(100,40,out,verifyCode); //验证码转换为图片流
            return R.success(new VerifyCodeVo(Base64Utils.encodeToString(out.toByteArray()), "image/jpeg", codeKey));
        } catch (IOException e) {
            log.error("获取图片验证码异常", e);

        }
        return R.fail("获取图片验证码异常");
    }

    @ApiOperation(value = "校验验证码")
    @ApiImplicitParam(name = "userCode", value = "用户输入的验证码", required = true)
    @PostMapping("/{userCode}")
    private R checkCode(HttpServletRequest request, @PathVariable("userCode") String userCode,@RequestParam("codeKey") String codeKey) {

        //从redis中取出验证码
        Object codeInRedis = redisTemplate.opsForValue().get("CODE_KEY_" + codeKey);
        log.info("USERCODE=" + userCode + ",CODE_IN_REDIS=" + codeInRedis);
        //准备返回给前端结果
        Map<String, Object> map = new HashMap<>();
        if (codeInRedis != null && codeInRedis.equals(userCode)) {
            // 如果验证成功，则清除token，防止重用；如果没有验证成功，则可以重复验证
            redisTemplate.delete("CODE_KEY_" + codeKey);
            map.put("result", "PASS");
        } else {
            map.put("result", "FAIL");
        }
        return R.success(map);

    }
}
